﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO.Ports;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BaseFunction;
using YFTOpenAPI.Model;
using YY.Model;


namespace YY.Web.MyAgent
{
    public partial class MySalesPerformanceBills : BaseFunction.LoginHelp
    {
        int page = 0;
        int rows = 0;
        private string strWhere = "";
        public double sum_accout = 0;
        private string end = "";
        private string ip = ConfigurationManager.AppSettings["ip"];
        private YY.Model.agent_users model = null;
        YY.Model.agent_dividend_record adr = new agent_dividend_record();
        private double currentPerformance;
        protected void Page_Load(object sender, EventArgs e)
        {
            model = base.GetSessionModel();
            if (!IsPostBack)
            {
                end = DateTime.Now.AddDays(-15).ToShortDateString() + "";
                ltl_end_time.Text = end;
                strWhere = string.Format("T2.dealtime < '{0}'", end);
                strWhere += string.Format(" AND T3.ContactAddress LIKE '%{0}%'", base.GetSessionModel().city);
                InitData(strWhere);
            }
            
        }


        /// <summary>
        /// 初始化操作
        /// </summary>
        private void InitData(string strWhere)
        {
            page = AspNetPager1.CurrentPageIndex; //当前页码
            rows = AspNetPager1.PageSize; //每页显示多少条
            string tabName = "dbo.PackageInfo T1 INNER JOIN dbo.Dealrecordlist T2 ON(T1.id=T2.packageguid) INNER JOIN dbo.tb_UserInfor T3 ON(T2.userguid=T3.FinancialAccount)";
            string columns = "T2.dealtime as sales_time,T3.UserName as user_name,T1.name as type_of_packages,T1.price as sales_bonus";
            string orderBy = "T2.dealtime desc";
            DataTable dt = MsSql2008.ExecSqlPagerPROCEDURE(columns, tabName, strWhere, orderBy, page, rows).Tables[2];
            rpt_sales_performance.DataSource = dt;
            rpt_sales_performance.DataBind();

            /*计算时间段统计*/
            ltl_sum.Text = MsSql2008.Query(string.Format("SELECT COUNT(*) FROM dbo.PackageInfo T1 INNER JOIN dbo.Dealrecordlist T2 ON(T1.id=T2.packageguid) INNER JOIN dbo.tb_UserInfor T3 ON(T2.userguid=T3.FinancialAccount) WHERE {0}", strWhere)).Tables[0].Rows[0][0] + "";
            /*A套餐*/
            ltl_A.Text = MsSql2008.Query(string.Format("SELECT COUNT(*) FROM dbo.PackageInfo T1 INNER JOIN dbo.Dealrecordlist T2 ON(T1.id=T2.packageguid) INNER JOIN dbo.tb_UserInfor T3 ON(T2.userguid=T3.FinancialAccount) WHERE {0} AND T1.name='A'", strWhere)).Tables[0].Rows[0][0] + "";
            /*B套餐*/
            ltl_B.Text = MsSql2008.Query(string.Format("SELECT COUNT(*) FROM dbo.PackageInfo T1 INNER JOIN dbo.Dealrecordlist T2 ON(T1.id=T2.packageguid) INNER JOIN dbo.tb_UserInfor T3 ON(T2.userguid=T3.FinancialAccount) WHERE {0} AND T1.name='B'", strWhere)).Tables[0].Rows[0][0] + "";
            /*C套餐*/
            ltl_C.Text = MsSql2008.Query(string.Format("SELECT COUNT(*) FROM dbo.PackageInfo T1 INNER JOIN dbo.Dealrecordlist T2 ON(T1.id=T2.packageguid) INNER JOIN dbo.tb_UserInfor T3 ON(T2.userguid=T3.FinancialAccount) WHERE {0} AND T1.name='C'", strWhere)).Tables[0].Rows[0][0] + "";
            /*总销售额*/
            var dt_sum = MsSql2008.Query(string.Format("SELECT SUM(CONVERT(DECIMAL(18,1),T1.price) ) FROM dbo.PackageInfo T1 INNER JOIN dbo.Dealrecordlist T2 ON(T1.id=T2.packageguid) INNER JOIN dbo.tb_UserInfor T3 ON(T2.userguid=T3.FinancialAccount) WHERE {0}", strWhere)).Tables[0].Rows[0][0];
            if (dt_sum == DBNull.Value)
            {
                sum_accout = 0;
            }
            else
            {
                sum_accout = double.Parse(dt_sum + "");
                ltl_sum_accout.Text = sum_accout + "";
                if (sum_accout >= 10 && sum_accout <= 5000000)
                {
                    ltl_point.Text = "0.04";
                    ltl_gain.Text = sum_accout * 0.04 + "元";
                }
                if (5000000 < sum_accout && sum_accout <= 20000000)
                {
                    ltl_point.Text = "0.06";
                    ltl_gain.Text = sum_accout * 0.06 + "元";
                }
                if (20000000 < sum_accout && sum_accout <= 50000000)
                {
                    ltl_point.Text = "0.08";
                    ltl_gain.Text = sum_accout * 0.08 + "元";
                }
                if (50000000 < sum_accout && sum_accout <= 100000000)
                {
                    ltl_point.Text = "0.1";
                    ltl_gain.Text = sum_accout * 0.1 + "元";
                }
            }
            /*当前的销售提成*/
            DataTable dtlist = MsSql2008.Query(string.Format("SELECT SUM(CONVERT(DECIMAL(18,0),sales_performance)) FROM dbo.tb_agent_dividend_record WHERE agent_id={0} AND account='{1}'", model.id, model.amount)).Tables[0];
            if (dtlist.Rows[0][0] != DBNull.Value)
            {
                //ltl_fund.Text = dt1.Rows[0][0]+"";//已提取的销售业绩
               double salesPerformance = Convert.ToDouble(dtlist.Rows[0][0]);
                /*根据销售业绩比例算提成*/
                 currentPerformance = sum_accout - salesPerformance;
                if (currentPerformance >= 10 && currentPerformance <= 5000000)
                {
                    hf_point.Value = "0.04";
                    ltl_fund.Text = currentPerformance * 0.04 + "元";
                }
                if (5000000 < currentPerformance && currentPerformance <= 20000000)
                {
                    hf_point.Value = "0.06";
                    ltl_fund.Text = currentPerformance * 0.06 + "元";
                }
                if (20000000 < currentPerformance && currentPerformance <= 50000000)
                {
                    hf_point.Value = "0.08";
                    ltl_fund.Text = currentPerformance * 0.08 + "元";
                }
                if (50000000 < currentPerformance && currentPerformance <= 100000000)
                {
                    hf_point.Value = "0.1";
                    ltl_fund.Text = currentPerformance * 0.1 + "元";
                }
            }
            else
            {
                currentPerformance =Convert.ToDouble(dt_sum);//当前业绩
                ltl_fund.Text = ltl_gain.Text + "元";
            }
            hf_account.Value = currentPerformance+"";
        }


        private void StrWhere()
        {
            string start = txt_starttime.Text;
            end = txt_endtime.Text;
            if (start != "")
            {
                strWhere = string.Format("T2.dealtime= '{0}'", start);
            }
            if (end != "")
            {
                strWhere = string.Format("T2.dealtime= '{0}'", end);
            }
            if (start != "" && end != "")
            {
                strWhere = string.Format("T2.dealtime between '{0}' and '{1}'", start, end);
            }
            InitData(strWhere);

            //ltl_start_time.Text = start;
            ltl_end_time.Text = end;
        }

        protected void LinkButtonSearch_Click(object sender, EventArgs e)
        {
            StrWhere();

        }

        #region  分页操作 buttom
        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            StrWhere();

        }
        #endregion
        /// <summary>
        /// 转出到分红账号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_Acount_Click(object sender, EventArgs e)
        {
            /*转出金额*/
            List<TransactionInfo> list = new List<TransactionInfo>();
            TransactionInfo transactioninfo = new TransactionInfo();
            transactioninfo.Payment_userinfoid = base.GetSessionModel().amount;//付款人id
            transactioninfo.Computationalway = "DisplayDividendWallet"; //费用类别 DisplayCashWallet（现金钱包） DisplayFrozen（冻结资金）  DisplayFinancialWallet（理财钱包） DisplayAdPointWallet（广告点钱包）DisplayIntegral（积分）DisplayDividendWallet(分红钱包)
            transactioninfo.Key = "yiyang";
            transactioninfo.Payment_MoneyAmount = ltl_fund.Text.Replace("元", "");//销售提成转出到分红账号
            transactioninfo.Computationalmethod = "1";// 1 加法(增加钱) 0 减法（减少钱）

            list.Add(transactioninfo);
            if (transactioninfo.Payment_MoneyAmount == "0")
            {
                MessageBox.Show(this.Page,"没有要转出的资金");
                return;
            }
            string transactionInfo = Newtonsoft.Json.JsonConvert.SerializeObject(list);
            string Additional = "";
            YFTOpenAPI.TransactionAPI openapi = new YFTOpenAPI.TransactionAPI("yiyang", ip, "27CAC2A3-F0C1-449C-8D59-62A9A263E48C");
            YFTOpenAPI.Model.ResponseData responseData = openapi.Transaction(transactionInfo, Additional);

            if (responseData.statuscode == 1)
            {
                adr.agent_id = model.id;
                adr.account = Guid.Parse(model.amount);
                adr.dividend_transfer_time = DateTime.Now;
                adr.dividend_transfer_allow_data = DateTime.Parse(ltl_end_time.Text);
                adr.Percentage_of_commission = hf_point.Value;//分红比例
                adr.sales_performance = Convert.ToDecimal(hf_account.Value);//当前业绩
                BaseFunction.StaticTableClass.agent_dividend_record_Help.bll_agent_dividend_record.Add(adr);
                //更新成功
                MessageBox.Show(this.Page, "已成功转出到分红账号");
            }
            else
            {
                //错误信息
                string message = responseData.message;
                MessageBox.Show(this.Page, "转账失败");
            }
        }
    }
}